<template>
  <div>
    <side-title>
      <span>
        <span>Name：</span>
        <span>{{ docName }}</span>
      </span>
    </side-title>
    <el-tabs class="mt-2" type="border-card">
      <el-tab-pane label="请求">
        <div class="p-2 mb-4 flex items-center">
          <el-select
            class="shrink-0"
            size="small"
            style="width: 80px"
            v-model="method"
          >
            <el-option
              v-for="item in methodOptions"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>

          <el-input size="small" :readonly="!isQuick" v-model="path"></el-input>
          <div class="ms-2 flex">
            <el-button
              :loading="requestLoading"
              @click="onRequest"
              type="primary"
              size="small"
              >运行</el-button
            >
            <el-button
              v-if="isCancel"
              @click="onCancel"
              type="warning"
              size="small"
              >取消</el-button
            >
            <el-button @click="onSave" size="small" :loading="saveLoading"
              >保存</el-button
            >
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="完整路径">
        <div class="p-2 mb-4 flex items-center">
          <el-select
            class="shrink-0"
            size="small"
            style="width: 80px"
            v-model="method"
          >
            <el-option
              v-for="item in methodOptions"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
          <el-input size="small" v-model="fullPath"></el-input>
          <div class="ms-2 flex">
            <el-button
              :loading="requestLoading"
              @click="onRequest"
              type="primary"
              size="small"
              >运行</el-button
            >
            <el-button @click="onSave" size="small" :loading="saveLoading"
              >保存</el-button
            >
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
    <side-title>请求参数</side-title>
    <el-tabs v-model="paramType" class="mt-2" type="border-card">
      <el-tab-pane name="parameter" label="parameter">
        <div class="p-2">
          <div
            class="flex items-center mb-2"
            v-for="(item, index) in queryParams"
            :key="item.id"
          >
            <el-input
              style="width: 180px"
              v-model="item.name"
              size="small"
              @input="onAddParameterRows(item)"
            ></el-input>
            <el-checkbox
              class="ms-2 me-2"
              disabled
              v-model="item.required"
            ></el-checkbox>
            <span class="me-2">=</span>
            <el-input
              v-model="item.value"
              size="small"
              placeholder="参数值"
              @input="onAddParameterRows(item)"
            ></el-input>
            <div
              @click="onDeleteParameter(item)"
              class="cursor-pointer flex items-center justify-center px-2 text-slate-400 hover:text-slate-950"
              :class="{ invisible: index === 0 }"
            >
              <i class="el-icon-delete"></i>
            </div>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane name="body" v-if="method !== 'GET'" label="Body">
        <div class="p-2">
          <el-radio-group v-model="bodyType">
            <el-radio label="">none</el-radio>
            <el-radio label="form">form</el-radio>
            <el-radio label="json">json</el-radio>
          </el-radio-group>
          <div class="mt-2" v-if="bodyType === 'json'">
            <v-jsoneditor
              v-model="json"
              ref="requestJsonComponent"
              :options="{ mode: 'code' }"
              :plus="false"
              height="400px"
            />
          </div>
          <div class="mt-2" v-else-if="bodyType === 'form'">
            <div
              class="flex items-center mb-2"
              v-for="(item, index) in formItems"
              :key="item.id"
            >
              <el-input
                class="shrink-0"
                style="width: 180px"
                v-model="item.field"
                size="small"
                @input="onAddFormRows(item)"
              ></el-input>
              <el-select
                style="width: 80px"
                class="grow-0 shrink-0 ms-2"
                size="small"
                placeholder="类型"
                v-model="item.type"
              >
                <el-option label="string" value="string"></el-option>
                <el-option label="file" value="file"></el-option>
              </el-select>
              <el-checkbox
                disabled
                class="ms-2 me-2"
                v-model="item.required"
              ></el-checkbox>
              <span class="me-2">=</span>
              <el-input
                v-if="item.type === 'string'"
                v-model="item.value"
                size="small"
                placeholder="参数值"
                @input="onAddFormRows(item)"
              ></el-input>
              <input
                @change="onBindFileForm($event, item)"
                class="grow"
                type="file"
                v-else
                @input="onAddFormRows(item)"
              />
              <div
                @click="onDeleteForm(item)"
                class="shrink-0 grow-0 cursor-pointer px-2 text-slate-400 hover:text-slate-950"
                :class="{ invisible: index === 0 }"
              >
                <i class="el-icon-delete"></i>
              </div>
            </div>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane name="headers" label="headers">
        <div class="p-2">
          <div
            class="flex items-center mb-2"
            v-for="(item, index) in headers"
            :key="item.id"
          >
            <el-input
              style="width: 180px"
              v-model="item.name"
              size="small"
              @input="onAddHeadersRows(item)"
            ></el-input>
            <span class="mx-2">=</span>
            <el-input
              v-model="item.value"
              size="small"
              placeholder="参数值"
              @input="onAddHeadersRows(item)"
            ></el-input>
            <div
              @click="onDeleteHeader(item)"
              class="cursor-pointer flex items-center justify-center px-2 text-slate-400 hover:text-slate-950"
              :class="{ invisible: index === 0 }"
            >
              <i class="el-icon-delete"></i>
            </div>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
    <!-- <el-collapse v-model="activeNames">
      <el-collapse-item title="Query Parameter" name="1">
        <div class="p-2">
          <div
            class="flex items-center mb-2"
            v-for="item in queryParams"
            :key="item.id"
          >
            <el-input
              style="width: 180px"
              v-model="item.name"
              size="small"
            ></el-input>
            <el-checkbox
              disabled
              class="ms-2 me-2"
              v-model="item.required"
            ></el-checkbox>
            <span class="me-2">=</span>
            <el-input
              v-model="item.value"
              size="small"
              placeholder="参数值"
            ></el-input>
          </div>
        </div>
      </el-collapse-item>
      <el-collapse-item title="Header" name="2">
        <div class="p-2">
          <div
            class="flex items-center mb-2"
            v-for="item in headers"
            :key="item.id"
          >
            <el-input
              style="width: 180px"
              v-model="item.name"
              size="small"
            ></el-input>
            <span class="mx-2">=</span>
            <el-input
              v-model="item.value"
              size="small"
              placeholder="参数值"
            ></el-input>
          </div>
        </div>
      </el-collapse-item>
      <el-collapse-item v-if="method !== 'get'" title="Body" name="3">
        <div class="p-2">
          <div v-if="bodyType === 'json'">
            <v-jsoneditor
              v-model="json"
              :options="{ mode: 'code' }"
              :plus="false"
              height="400px"
              @error="onError"
            />
          </div>
          <div v-else-if="bodyType === 'form'">
            <div
              class="flex items-center mb-2"
              v-for="item in formItems"
              :key="item.id"
            >
              <el-input
                style="width: 180px"
                v-model="item.field"
                size="small"
              ></el-input>
              <el-checkbox
                disabled
                class="ms-2 me-2"
                v-model="item.required"
              ></el-checkbox>
              <span class="me-2">=</span>
              <el-input
                v-if="item.type === 'text'"
                v-model="item.value"
                size="small"
                placeholder="参数值"
              ></el-input>
              <input type="file" v-else />
            </div>
          </div>
        </div>
      </el-collapse-item>
    </el-collapse> -->

    <side-title>
      <span>返回数据</span>
      <el-tag
        v-if="status"
        class="ms-4 align-bottom"
        :type="status >= 200 && status < 300 ? 'success' : 'danger'"
        >{{ status }}</el-tag
      >

      <span class="ms-4 text-sm" v-if="requestTime">
        <span>{{ requestTime }}</span>
        <span>s</span>
      </span>
    </side-title>

    <div
      class="mt-2 relative"
      element-loading-text="请求中......"
      v-loading="requestLoading"
    >
      <el-tabs type="border-card">
        <el-tab-pane v-if="resType === 'json'" label="Json">
          <v-jsoneditor
            class="res"
            v-model="res"
            :options="{ mode: 'code', onEditable: () => {} }"
            readonly
            :plus="true"
            height="400px"
          />
        </el-tab-pane>
        <el-tab-pane v-if="resType === 'text'" label="Text">
          <div style="height: 400px" :id="editUid"></div>
        </el-tab-pane>
        <el-tab-pane v-if="resType === 'blob'" label="File">
          <el-button @click="onDownLoad" icon="el-icon-download"
            >点击下载</el-button
          >
        </el-tab-pane>
        <!-- <el-tab-pane label="Headers">角色管理</el-tab-pane> -->
        <!-- <el-tab-pane label="定时任务补偿">定时任务补偿</el-tab-pane> -->
      </el-tabs>
    </div>
    <!-- <el-input type="textarea" :rows="20" readonly v-model="res"></el-input> -->
  </div>
</template>

<script>
import axios from "axios";
import ace from "ace-code";
import { onMounted, reactive, ref, toRef, watch } from "@vue/composition-api";
import SideTitle from "@/components/SideTitle/index.vue";
import { Message } from "element-ui";
export default {
  props: {
    env: Object,
    isQuick: Boolean,
  },
  components: {
    SideTitle,
  },
  setup(props, { emit }) {
    const editUid = Date.now()

    let i = 1;
    const activeNames = reactive([]);
    const method = ref("POST");
    watch(method, () => {
      if (method.value === "GET") {
        bodyType.value = "";
      }
    });
    const methodOptions = ["GET", "POST", "PUT", "DELETE"];
    const path = ref("");
    const fullPath = ref("");
    watch(toRef(props, "env"), () => {
      console.log("env");
      if (path.value) {
        let tmpPath = path.value;
        if (props.env && props.env.variable) {
          props.env.variable.forEach((item) => {
            tmpPath = tmpPath.replace(
              new RegExp(`\\{\\{.*?${item.key}.*?\\}\\}`, "g"),
              item.value
            );
          });
        }
        fullPath.value = tmpPath;
      }
    });
    watch(path, () => {
      if (path.value) {
        console.log("path");
        let tmpPath = path.value;
        if (props.env && props.env.variable) {
          props.env.variable.forEach((item) => {
            tmpPath = tmpPath.replace(
              new RegExp(`\\{\\{.*?${item.key}.*?\\}\\}`, "g"),
              item.value
            );
          });
        }
        fullPath.value = tmpPath;
      }
    });

    const queryParams = ref([
      // {
      //   id: 1,
      //   name: "",
      //   value: "",
      //   required: false,
      //   in: "query",
      //   schema: {
      //     type: "number",
      //   },
      // },
      // {
      //   id: 2,
      //   name: "",
      //   value: "",
      //   required: true,
      //   in: "query",
      //   schema: {
      //     type: "number",
      //   },
      // },
      // {
      //   id: 3,
      //   name: "",
      //   value: "",
      //   required: true,
      //   in: "query",
      //   schema: {
      //     type: "string",
      //   },
      // },
    ]);
    function onDeleteParameter(item) {
      console.log(item);
      const index = queryParams.value.findIndex((it) => it.id === item.id);
      queryParams.value.splice(index, 1);
      console.log(queryParams);
    }

    function onAddParameterRows(row) {
      const id = row.id;
      const index = queryParams.value.findIndex((item) => item.id === id);
      if (index === queryParams.value.length - 1) {
        if (row.name || row.value) {
          queryParams.value.push({
            id: ++i,
            name: "",
            value: "",
          });
        }
      }
    }

    const headers = ref([
      // {
      //   id: 1,
      //   name: "Content-Type",
      //   value: "application/json",
      // },
    ]);

    function onDeleteHeader(item) {
      const index = headers.value.findIndex((it) => it.id === item.id);
      headers.value.splice(index, 1);
    }

    function onAddHeadersRows(row) {
      const id = row.id;
      const index = headers.value.findIndex((item) => item.id === id);
      if (index === headers.value.length - 1) {
        if (row.name || row.value) {
          headers.value.push({
            id: ++i,
            name: "",
            value: "",
          });
        }
      }
    }

    const bodyType = ref("");
    const json = ref("");
    const jsonObj = ref([
      {
        id: 1,
        field: "root",
        root: true,
        mock: "",
        type: "object",
        title: "",
        description: "",
        required: false,
        children: [],
      },
    ]);

    function parse(obj, parent) {
      const list = [];
      Object.keys(obj).forEach((k) => {
        const dto = obj[k];
        if (["object"].includes(dto.type)) {
          const node = {
            parent,
            id: i++,
            root: false,
            field: k,
            type: dto.type,
            description: dto.description,
            // hasExpand: true,
            children: [],
          };
          node.children = parse(dto.properties, node);
          list.push(node);
        } else if (["array"].includes(dto.type)) {
          const node = {
            parent,
            id: i++,
            root: false,
            field: k,
            type: dto.type,
            description: dto.description,
            // hasExpand: true,
            children: [],
          };
          node.children =
            dto.items.type === "object"
              ? [parse(dto.items, node)]
              : [
                  {
                    id: i++,
                    items: true,
                    field: "items",
                    type: dto.items.type,
                    children: [],
                  },
                ];
          list.push(node);
        } else {
          list.push({
            parent,
            id: i++,
            description: dto.description,
            type: dto.type,
            field: k,
            children: [],
          });
        }
      });
      return list;
    }

    function parseRoot(root) {
      console.log(root);
      if (root.type === "object") {
        const val = {};
        root.children.forEach((sub) => {
          val[sub.field] = parseRoot(sub);
        });
        return val;
      } else if (root.type === "array") {
        const val = [parseRoot(root.children[0])];
        return val;
      } else if (["number", "integer"].includes(root.type)) {
        return 1;
      } else if ("string" === root.type) {
        return "string";
      } else {
        return "";
      }
    }

    const formItems = ref([
      // {
      //   id: 1,
      //   field: "orgCode",
      //   type: "text",
      //   example: "",
      //   value: "",
      //   required: true,
      // },
      // {
      //   id: 2,
      //   field: "file",
      //   type: "file",
      //   example: "",
      //   value: "",
      //   required: true,
      // },
    ]);

    function onDeleteForm(item) {
      console.log(formItems.value);
      const index = formItems.value.findIndex((it) => it.id === item.id);
      formItems.value.splice(index, 1);
    }

    function onBindFileForm(e, item) {
      item.value = e.target.files[0];
      console.log(item.value);
    }

    function onAddFormRows(row) {
      const id = row.id;
      const index = formItems.value.findIndex((item) => item.id === id);
      if (index === formItems.value.length - 1) {
        if (row.field || row.value) {
          formItems.value.push({
            id: ++i,
            name: "",
            value: "",
            type: "string",
          });
        }
      }
    }
    const requestLoading = ref(false);
    const isCancel = ref(false);
    let timer = null;
    let _timestamp = Date.now();

    function onCancel() {
      window.postMessage({
        __SIGNAL__: "cancel",
        timestamp: _timestamp,
        data: { __SIGNAL__: "cancel", timestamp: _timestamp },
      });
      window.onmessage = function (e) {
        const { timestamp, data, __SIGNAL__ } = e.data;

        if (__SIGNAL__ === "res" && timestamp === _timestamp) {
          requestLoading.value = false;
          isCancel.value = false;
          clearTimeout(timer);
          resType.value = "text";
          editor.setValue("请求取消");
        }
      };
    }

    async function onRequest() {
      timer = setTimeout(() => {
        isCancel.value = true;
      }, 2000);
      editor.setValue("");
      res.value = "";
      requestTime.value = "";
      status.value = "";
      const params = {};
      const resultHeaders = {};
      const forms = [];
      resType.value = "text";
      blobUrl = "";
      queryParams.value.forEach((query) => {
        if (query.name) {
          params[query.name] = query.value;
        }
      });
      headers.value.forEach((item) => {
        if (item.name) {
          resultHeaders[item.name] = item.value;
        }
      });
      formItems.value.forEach((item) => {
        if (item.field && item.value) {
          forms.push(item);
        }
      });
      if (bodyType.value === "json") {
        let bool = false;
        Object.keys(resultHeaders).forEach((k) => {
          if (k.toUpperCase() === "CONTENT-TYPE") {
            bool = true;
            resultHeaders[k] = "application/json";
          }
        });
        if (!bool) {
          resultHeaders["content-type"] = "application/json";
        }
      }
      let data = null;
      if (method.value !== "GET") {
        if (bodyType.value === "json") {
          data = json.value;
        } else if (bodyType.value === "form") {
          // const formData = new FormData();
          for (const item of forms) {
            if (item.value instanceof File) {
              async function transFormFileToArray() {
                return new Promise((resolve) => {
                  var arrayBuffer;
                  var fileReader = new FileReader();
                  fileReader.onload = function (event) {
                    arrayBuffer = event.target.result;
                    resolve(Array.from(new Uint8Array(arrayBuffer)));
                  };
                  fileReader.readAsArrayBuffer(item.value);
                });
              }
              item.value = {
                name: item.value.name,
                array: await transFormFileToArray(),
                type: item.value.type,
              };
            }
          }
          data = forms;
        }
      }

      const requestParam = {
        url: fullPath.value,
        method: method.value,
        headers: {
          ...resultHeaders,
        },
        params: {
          ...params,
        },
        type: bodyType.value,
      };
      if (data) {
        requestParam.body = data;
      }
      _timestamp = Date.now();
      function exec(options, callback) {
        if (!options.method) {
          options.method = 'GET'
        }
        window.postMessage({
          __SIGNAL__: "req",
          timestamp: _timestamp,
          data: { __SIGNAL__: "req", timestamp: _timestamp, ...options },
        });
        window.onmessage = function (e) {
          const { timestamp, data, __SIGNAL__ } = e.data;
          if (__SIGNAL__ === "res" && timestamp === _timestamp) {
            callback(timestamp, data);
          }
        };
      }
      window.fetchExec = function (url, o) {
        console.log(url)
        return new Promise((resolve) => {
          exec({ url, ...o }, (timestamp, data) => {
            resolve(data.data);
          });
        });
      };
      requestLoading.value = true;
      console.log(props.env.preHandle)
      if (props.env.preHandle) {
        const AsyncFunction = async function () {}.constructor;
        const handleFun = new AsyncFunction("req", props.env.preHandle);
        handleFun(requestParam).then(() => {
          const startDate = new Date();
          exec(requestParam, (timestamp, data) => {
            console.log(timestamp, data);
            if (data.responseType === "json") {
              res.value = data.data;
            } else if (data.responseType === "text") {
              editor.setValue(data.data);
            } else if (data.responseType === "blob") {
              const u = new Uint8Array(data.data);
              const blob = new Blob([u], { type: "application/octet-stream" });
              blobUrl = URL.createObjectURL(blob);
            } else if (data.responseType === "error") {
              data.responseType = "text";
              editor.setValue(data.data);
              Message({
                message: "插件异常：" + data.data,
                type: "error",
              });
            }
            status.value = data.status;
            resType.value = data.responseType;
            requestLoading.value = false;
            isCancel.value = false;
            clearTimeout(timer);
            const endDate = new Date();
            requestTime.value = (endDate - startDate) / 1000;
          });
        });
      } else {
        const startDate = new Date();
        exec(requestParam, (timestamp, data) => {
          console.log(timestamp, data);
          if (data.responseType === "json") {
            res.value = data.data;
          } else if (data.responseType === "text") {
            editor.setValue(data.data);
          } else if (data.responseType === "blob") {
            const u = new Uint8Array(data.data);
            const blob = new Blob([u], { type: "application/octet-stream" });
            blobUrl = URL.createObjectURL(blob);
          } else if (data.responseType === "error") {
            data.responseType = "text";
            editor.setValue(data.data);
            Message({
              message: "插件异常：" + data.data,
              type: "error",
            });
          }
          status.value = data.status;
          resType.value = data.responseType;
          requestLoading.value = false;
          isCancel.value = false;
          clearTimeout(timer);
          const endDate = new Date();
          requestTime.value = (endDate - startDate) / 1000;
        });
      }
      console.log(requestParam);

      // axios(requestParam).then((r) => {
      //   console.log(r)
      //   res.value = r.data;
      // });
    }
    function getQuickDoc() {
      const doc = {
        method: method.value,
        path: path.value,
        parameters: {
          queryParams: queryParams.value
            .filter((item) => item.name)
            .map(({ id, ...result }) => result),
          headers: headers.value
            .filter((item) => item.name)
            .map(({ id, ...result }) => result),
        },
        requestBody: {},
      };
      if (json.value) {
        doc.requestBody["application/json"] = json.value;
      }
      if (formItems.value) {
        doc.requestBody["multipart/form-data"] = formItems.value
          .filter((item) => item.field)
          .map(({ id, value, ...result }) => ({
            value: typeof value === "string" ? value : null,
            ...result,
          }));
      }
      doc.requestBody["default"] = bodyType.value;
      return doc;
    }
    const saveLoading = ref(false);
    function onSave() {
      saveLoading.value = true;
      emit("save", getQuickDoc(), () => {
        saveLoading.value = false;
      });
    }

    const res = ref({});
    const resType = ref("text");
    const status = ref("");
    let blobUrl = "";
    function onDownLoad() {
      const a = document.createElement("a");
      a.href = blobUrl;
      a.click();
    }
    let editor = null;
    onMounted(() => {
      watch(
        resType,
        () => {
          if (resType.value === "text") {
            editor = ace.edit(editUid + '');
            editor.setValue("");
          }
        },
        { flush: "post", immediate: true }
      );
    });

    const requestTime = ref("");
    const paramType = ref("parameter");
    const docName = ref('')

    const requestJsonComponent = ref(null)
    return {
      requestJsonComponent,
      editUid,
      activeNames,
      method,
      methodOptions,
      path,
      fullPath,
      queryParams,
      onAddParameterRows,
      onDeleteParameter,

      headers,
      onDeleteHeader,
      onAddHeadersRows,
      json,
      res,
      resType,
      status,
      formItems,
      onDeleteForm,
      onAddFormRows,
      onBindFileForm,
      bodyType,
      requestTime,
      docName,
      isCancel,

      onRequest,
      onCancel,
      onDownLoad,
      getQuickDoc,
      saveLoading,
      onSave,
      requestLoading,
      paramType,
      setQuickDoc(doc) {
        window.onmessage = () => {};
        window.postMessage({
          __SIGNAL__: "cancel",
          timestamp: Date.now(),
          data: { __SIGNAL__: "cancel", timestamp: Date.now() },
        });
        isCancel.value = false;
        clearTimeout(timer);
        requestLoading.value = false;
        paramType.value = "parameter";
        method.value = "";
        path.value = "";
        queryParams.value = [];
        formItems.value = [];
        headers.value = [];
        json.value = {};
        bodyType.value = "";
        res.value = "";
        editor.setValue("");

        console.log(doc, "ed");
        docName.value = doc.summary
        method.value = doc.method;
        path.value = doc.path;
        if (doc.parameters) {
          queryParams.value = doc.parameters.queryParams ? JSON.parse(JSON.stringify(doc.parameters.queryParams)) : [];
          headers.value = doc.parameters.headers ? JSON.parse(JSON.stringify(doc.parameters.headers)) : [];
        }
        // console.log(requestJsonComponent.value.editor)
        if (doc.requestBody) {
          json.value = doc.requestBody["application/json"] || {};
        
          console.log(json, '------------')
          if (doc.requestBody["multipart/form-data"]) {
            formItems.value = doc.requestBody["multipart/form-data"].map(
              (item) => ({
                id: ++i,
                ...item,
              })
            );
          } else {
            formItems.value = [];
          }
          bodyType.value = doc.requestBody.default || "";
        }
        queryParams.value.push({ name: "", value: "", id: ++i });
        headers.value.push({ name: "", value: "", id: ++i });
        formItems.value.push({
          id: ++i,
          field: "",
          value: "",
          type: "string",
        });
      },
      setDoc(doc) {
        paramType.value = "parameter";
        method.value = doc.method;
        path.value = doc.path;
        if (doc.parameters) {
          activeNames.push("1");
          queryParams.value = doc.parameters
            .filter((item) => item.in === "query")
            .map((item) => ({
              id: ++i,
              value: "",
              ...item,
            }));
          queryParams.value.push({ name: "", value: "", id: ++i });
          headers.value = doc.parameters
            .filter((item) => item.in === "header")
            .map((item) => ({
              id: ++i,
              value: "",
              ...item,
            }));
          headers.value.push({ name: "", value: "", id: ++i });
        } else {
          queryParams.value.push({ name: "", value: "", id: ++i });
          headers.value.push({ name: "", value: "", id: ++i });
        }
        if (doc.requestBody && doc.requestBody.content) {
          const content = doc.requestBody.content;
          activeNames.push("3");
          if (
            content &&
            content["multipart/form-data"] &&
            content["multipart/form-data"].schema
          ) {
            const schema = content["multipart/form-data"].schema;
            formItems.value = Object.entries(schema.properties).map(
              ([field, item]) => {
                const it = {
                  id: ++i,
                  field,
                  value: "",
                  ...item,
                };
                return it;
              }
            );
            formItems.value.push({
              id: ++i,
              field: "",
              value: "",
              type: "string",
            });
            bodyType.value = "form";
          }
          if (
            content &&
            content["application/json"] &&
            content["application/json"].schema &&
            content["application/json"].schema.properties
          ) {
            jsonObj.value[0].children = parse(
              content["application/json"].schema.properties,
              json.value[0]
            );

            const obj = parseRoot(jsonObj.value[0]);
            json.value = obj;
            bodyType.value = "json";
          }
        } else {
          formItems.value.push({
            id: ++i,
            type: "string",
            field: "",
            value: "",
          });
        }
        console.log(formItems.value);
      },
    };
  },
};
</script>

<style scoped>
.res >>> .jsoneditor-menu {
  background-color: black;
}
.res >>> .max-btn {
  display: block;
  color: #fff;
}
</style>